(function($){
	$.fn.XuiFileUpload = function(data){
		//继承参数
		$.extend(Fun.config , data);
		Fun.init.call($(this));
	};
	var Fun = {
		config:{
			url:"",
			multiple:false,
			input:'<input type="file" style="display:none"/><span class="UploadBtn" style="position:absolute;top:0;left:0;display:inline-block;width:100%;height:100%;background:none;"></span>',
			fileList:[],
			uploadStart:null,
			upload:null,
			uploadEnd:null,
			fileType:/\w\.(jpg|png|gif|bmp)$/,
			fileSize:null,
		},
		//初始化
		init:function(){
			//添加input
			$(this).css("position","relative");
			$(this).append(Fun.config.input);
			Fun.config.multiple && $(this).find("input").attr("multiple" , "multiple");
			$(this).each(function(){
				//绑定事件
				Fun.bindEv.call($(this));
			});
		},
		bindEv:function(){
			//点击
			var self = $(this);
			self.find(".UploadBtn").on("click" , function(){
				self.find("input").val("");
				self.find("input").click();
			});
			//选择文件
			self.find("input").on("change" , function(e){
				Fun.uploadStart(e);
			});
		},
		//选择文件后 
		uploadStart:function(e){
			var files = e.target.files || e.dataTransfer.files,
				config = Fun.config,
				result = true,
				read = "",
				filePath = [],
				filesArrry = [];
			$.each(files, function(index){
				//类型判断
//				if(!/\w\.(jpg|png|gif|bmp)$/.test(files[index].type)){
//					config.verification("类型" , files[index].name , index+1);
//					return result = false;
//				};
				//大小判断
				if(config.fileSize && files[index].size > config.fileSize){
					config.verification("图片大小" , files[index].name , index+1);
					return result = false;
				};
				//读取路径
				//实例化读取
				read = new FileReader();
				read.readAsDataURL(files[index]);
				read.onload = function(){
					filePath.push(this.result);
					filesArrry = files[index];
					if(index+1 === files.length && result){
						config.uploadStart && config.uploadStart(filePath);
						Fun.upload(filesArrry);
					}
				};
			});
		},
		upload:function(files){
			var xhr = new XMLHttpRequest(),
				formData = new FormData(),
				complete = 0;
			formData.append("upload" , files);
			xhr.open("POST" , Fun.config.url);
			//进度
			xhr.upload.onprogress = function(event){
				if(event.lengthComputable){
	　　　　　			complete = event.loaded / event.total * 100 | 0;
					Fun.config.upload(complete);
				};
			};
			xhr.onload = function(){
				Fun.config.uploadEnd(xhr.response);
			};
			xhr.send(formData);
		}
	};
})(jQuery)
